"""Performance record schemas for request/response validation."""

from datetime import date
from typing import Any, Optional

from pydantic import BaseModel, Field, field_validator


class PerformanceRecordBase(BaseModel):
    """Base schema for performance record."""

    record_date: date = Field(..., description="Date of the performance record")
    deals_count: int = Field(ge=0, default=0, description="Number of closed deals")
    showings_count: int = Field(ge=0, default=0, description="Number of property showings")
    new_customers_count: int = Field(ge=0, default=0, description="Number of new customers")
    followup_visits_count: int = Field(ge=0, default=0, description="Number of follow-up visits")

    @field_validator(
        "deals_count", "showings_count", "new_customers_count", "followup_visits_count"
    )
    @classmethod
    def validate_non_negative(cls, v: int) -> int:
        """Ensure counts are non-negative."""
        if v < 0:
            raise ValueError("Count must be non-negative")
        return v


class PerformanceRecordCreate(PerformanceRecordBase):
    """Schema for creating a performance record."""

    user_id: int = Field(..., description="ID of the employee")


class PerformanceRecordUpdate(BaseModel):
    """Schema for updating a performance record."""

    deals_count: Optional[int] = Field(None, ge=0)
    showings_count: Optional[int] = Field(None, ge=0)
    new_customers_count: Optional[int] = Field(None, ge=0)
    followup_visits_count: Optional[int] = Field(None, ge=0)


class PerformanceRecordResponse(PerformanceRecordBase):
    """Schema for performance record response."""

    id: int
    user_id: int
    daily_reward: float = Field(..., description="Calculated daily reward (max 100)")
    created_at: date
    updated_at: date

    class Config:
        from_attributes = True


class PerformanceRecordWithUser(PerformanceRecordResponse):
    """Performance record with user information."""

    user_name: str = Field(..., description="Employee name")


class PerformanceImportRow(BaseModel):
    """Schema for a single row in Excel import."""

    name: str = Field(..., min_length=1, description="Employee name")
    record_date: date = Field(..., description="Record date")
    deals_count: int = Field(ge=0, default=0)
    showings_count: int = Field(ge=0, default=0)
    new_customers_count: int = Field(ge=0, default=0)
    followup_visits_count: int = Field(ge=0, default=0)


class PerformanceImportResult(BaseModel):
    """Result of performance record import."""

    total_rows: int = Field(..., description="Total rows in file")
    success_count: int = Field(..., description="Successfully imported records")
    error_count: int = Field(..., description="Failed records")
    errors: list[str] = Field(default_factory=list, description="Error messages")


class PerformanceStatsQuery(BaseModel):
    """Query parameters for performance statistics."""

    user_id: Optional[int] = None
    start_date: Optional[date] = None
    end_date: Optional[date] = None


class PerformanceMonthlySummary(BaseModel):
    """Monthly performance summary for an employee."""

    user_id: int
    user_name: str
    month: str = Field(..., description="Month in YYYY-MM format")
    total_deals: int
    total_showings: int
    total_new_customers: int
    total_followups: int
    total_reward: float = Field(..., description="Total reward for the month")
    avg_daily_reward: float = Field(..., description="Average daily reward")
    working_days: int = Field(..., description="Number of days with records")


class PerformanceDashboard(BaseModel):
    """Dashboard data for performance overview."""

    top_earners: list[dict[str, Any]] = Field(..., description="Top 10 employees by monthly reward")
    monthly_trends: list[dict[str, Any]] = Field(..., description="Monthly reward trends")
    activity_breakdown: dict[str, Any] = Field(..., description="Breakdown of activities by type")
